package cool.taomu.box.kademlia.test

import cool.taomu.toolkit.crypto.Base64
import cool.taomu.toolkit.service.kademlia.utils.BEncodeUtils
import cool.taomu.toolkit.service.kademlia.utils.TorrentUtils
import java.io.File
import java.io.FileInputStream
import java.security.MessageDigest
import java.util.Map
import org.apache.commons.io.IOUtils
import org.junit.jupiter.api.Test

class BEncodeTest {
	
	
    @Test
    def void t2() {
    	var a = "./usecase/192.168.1.4.18080.local.json"
    	TorrentUtils.create(new File(a),262144L)
    }

    @Test
    def void t() {
        var filename = "192.168.1.4.18080.local.torrent"
        var hash = BEncodeUtils.read("./usecase/" + filename)
        var infoHash = hash.get("info") as Map<String, Object>
        println(String.format("文件 %s 的 infoHash \n %s", filename, infoHash))
        var pieces = infoHash.get("pieces") as String
        var piecesBytes = new Base64(pieces.bytes).decode();
        println("pieces.size:" + piecesBytes.size)
        val piecesHash = BEncodeUtils.getPieceHashes(piecesBytes)
        println(BEncodeUtils.bytesToHex(piecesHash.get(0)))
        try(var input = new FileInputStream("./usecase/192.168.1.4.18080.local.json")) {
            var sha1 = MessageDigest.getInstance("SHA-1");
            var inputBytes = IOUtils.toByteArray(input)
            var byte[] sha1Hash = sha1.digest(inputBytes);
            var sha1Str = BEncodeUtils.bytesToHex(sha1Hash)
            println(sha1Str)
        }
        
    // LOG.info("文件 {} 的 pieces size \n {}", filename, pieces.size)
    }
}
